#!/usr/bin/python

import apt
import re

cache = apt.Cache()

default_packages = set()
# these are false default as you have some alternatives deps that are taken
# into account like file-roller depends zip | p7zip-full
# -> p7zip-full won't be listed
false_defaults = set(['p7zip-full', 'vim-gnome', 'vim'])

# default whitelist, completed then by ubuntu-restricted-extras deps
whitelist = set(['flashplugin-nonfree', 'gnash',
'gstreamer0.10-fluendo-mpegdemux', 'swfdec-gnome',
'swfdec-mozilla', 'ubuntu-restricted-extras'])
blacklist_regexp = re.compile('.*-dev')

desktop_pkg_file_pattern = re.compile('/usr/share/applications/.*\.desktop')
bin_file_pattern = re.compile('/bin/.*')
sbin_file_pattern = re.compile('/sbin/.*')
usr_bin_file_pattern = re.compile('/usr/bin/.*')
usr_sbin_file_pattern = re.compile('/usr/sbin/.*')

def get_dep_rec_list(root_package, default_packages, recursive=True):
    '''Get list of dep of package_root'''

    for relations in (root_package.candidate.dependencies,
                      root_package.candidate.recommends):
        for dep in relations:
            for or_dep in dep.or_dependencies:
                if or_dep.name not in default_packages:
                    default_packages.add(or_dep.name)
                    try:
                        if recursive:
                            get_dep_rec_list(cache[or_dep.name], default_packages)
                    except KeyError:
                        pass
get_dep_rec_list(cache['ubuntu-desktop'], default_packages)
get_dep_rec_list(cache['ubuntu-minimal'], default_packages)
get_dep_rec_list(cache['ubuntu-standard'], default_packages)
default_packages -= false_defaults

#add to the whitelist ubuntu-restricted-extras direct dep
get_dep_rec_list(cache['ubuntu-restricted-extras'], whitelist, recursive=False)

# get list of all apps installed
candidate_pkg = set()
for pkg in cache:
    if (pkg.is_installed and not pkg.is_auto_installed and not
        pkg.priority in ('required', 'important')):
        if pkg.name in whitelist:
            candidate_pkg.add(pkg.name)
        elif blacklist_regexp.match(pkg.name):
            continue
        else:
            for pkg_file in pkg.installed_files:
                if (desktop_pkg_file_pattern.match(pkg_file) or
                    bin_file_pattern.match(pkg_file) or
                    sbin_file_pattern.match(pkg_file) or
                    usr_bin_file_pattern.match(pkg_file) or
                    usr_sbin_file_pattern.match(pkg_file)):
                    candidate_pkg.add(pkg.name)
                    break

# archive those not in default set
pkg_to_archive = set()
pkg_to_archive = candidate_pkg - default_packages

#debug
pkg_name_list = [pkg_name for pkg_name in pkg_to_archive]
#for pkg_name in default_packages:
#    if pkg_name == 'p7zip-full':
#        print "grrrr"
for name in pkg_name_list:
    print name
